﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WTwitter.Model.UserData;

namespace WTwitter.Model.Framework {
	/// <summary>
	/// 複数の入力ソースを１まとめに表示するタイムライン
	/// </summary>
	class MultiSourceTimeline : ITimeline {
		#region private member
		private AuthInfo _info;
		private List<ITimelineItem> _allItems = new List<ITimelineItem>();
		private List<ITimeline> _sourceTimelines = new List<ITimeline>();
		#endregion

		public MultiSourceTimeline(IEnumerable<ITimeline> sources, AuthInfo info) {
			_info = info;
			foreach (var timeline in sources) {
				AddTimeline(timeline);
			}

			TimelineRead += (sender, e) => { };
		}

		public MultiSourceTimeline(AuthInfo info)
			: this(Enumerable.Empty<ITimeline>(), info){

		}

		public void AddTimeline(ITimeline target) {
			_sourceTimelines.Add(target);
			target.TimelineRead += this.TimelineRead;
		}

		public void RemoveTimeline(ITimeline target) {
			_sourceTimelines.Remove(target);
			target.TimelineRead -= this.TimelineRead;
		}

		private void OnItemsAdded(object sender, ReadTimelineEventArgs e) {
			if (e.ResultType != TimelineReadResult.ReadNewItems) {
				return;
			}

			var newItems = e.NewItems.Except(this.AllItems);
			_allItems.AddRange(newItems);
			TimelineRead(this, new ReadTimelineEventArgs(newItems.ToList<ITimelineItem>()));
		}

		#region ITimeline メンバ


		public void UpdateAsync() {
		}

		public void ForceUpdate() {
			foreach (var timeline in this._sourceTimelines) {
				timeline.ForceUpdate();
			}
		}

		public event EventHandler<ReadTimelineEventArgs> TimelineRead;

		public List<ITimelineItem> AllItems {
			get { return _allItems; }
		}

		public bool IsUpdatable {
			get {
				if (_sourceTimelines.Count > 0 && _sourceTimelines.Any(timeline => timeline.IsUpdatable)) {
					return true;
				} else {
					return false;
				}
			}
		}

		public WTwitter.Model.UserData.AuthInfo AuthInfo {
			get { return _info; }
		}

		#endregion
	}
}
